package com.jeeplus.modules.work.utils;

import java.io.*;

public class ProgramRunningCheck {
    public static Boolean startReaderSV () {
        String programPath = "D:\\四川社保卡读卡中间件服务\\DC_ReaderSV.exe"; // 要检测的程序路径

        if (isProgramRunning(programPath)) {
            System.out.println(programPath + " is running.");
            return false;
        } else {
            System.out.println(programPath + " is not running.");
            try{
                Runtime.getRuntime().exec("cmd /c "+programPath);
                return true;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return false;
    }

    public static boolean isProgramRunning(String programPath) {
        boolean isRunning = false;
        String os = System.getProperty("os.name").toLowerCase();

        File programFile = new File(programPath);
        String programName = programFile.getName();

        try {
            ProcessBuilder processBuilder;
            if (os.contains("win")) {
                // Windows系统
                processBuilder = new ProcessBuilder("tasklist");
            } else {
                // 非Windows系统
                processBuilder = new ProcessBuilder("ps", "-e");
            }

            Process process = processBuilder.start();
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(programName)) {
                    isRunning = true;
                    break;
                }
            }

            reader.close();
            inputStream.close();
            process.destroy();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return isRunning;
    }
}
